var express = require('express');
var router = express.Router();
var moment = require('moment');
var fs = require('fs');
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;

moment.locale('zh-cn');

function getRandomNum(Min, Max) {
    var Range = Max - Min;
    var Rand = Math.random();
    return (Min + Math.round(Rand * Range));
}

var pad = function(tbl) {
    return function(num, n){
        n = n - (''+num).length;
        // console.log('asdasd=='+n);
        return (0 >= n) ? num : (tbl[n] || (tbl[n] = Array(n + 1).join(0)))+num;
    }    
}([]);

function createModFile(urllist) {
    urllist = urllist.trim();
    // 读取模板文件
    var templateFile = 'views/go_template.mod';
    var data = fs.readFileSync(templateFile, "utf-8");
    // 替换其中的占位符
    data = data.replace('<%= url %>', urllist);
    // 构造输出的临时文件的文件名
    var randNum = getRandomNum(0, 999999);
    var filePath = '/tmp/go_' + randNum + '.mod';
    // 写文件
    fs.writeFileSync(filePath, data);

    return filePath;
}

function gomod_build_process(req, res, fileKey) {
    var fn = (function (error, stdout, stderr) {
        var msg = '';
        if (error !== null) {
            msg = '调用GO MOD时发生错误: <br/>' + (error + '').replace(/\n/g, '<br/>\n');
        } else if (stderr.length > 0) {
            msg = '调用GO MOD时发生错误: <br/>' + (stderr + '').replace(/\n/g, '<br/>\n');
        } else {
            msg = '<br/>'+
                stdout.replace(/\n/g, '<br/>\n') + '<br/><br/>'+
                '<a href="/download?id=' + fileKey + '">下载结果文件（一小时内有效）</a>';
        }
        res.render('upload', { title: '依赖提取工具(GO-MOD版)', filekey: fileKey, message: msg });
    });
    return fn;
}

//粘贴的一组依赖的提取服务
router.post('/uploadsome', function (req, res, next) {
    var urllist = req.body.urllist;

    if (urllist && urllist.length > 0) {
        // res.send('文件上传成功');
        // console.log(req.file);
        var filePath = createModFile(urllist);
        console.log('收到一个请求：' + urllist);
        if (filePath.length == 0) {
            res.send('文本格式不正确！');
        }

        var formatDate = moment().format('YYYYMMDDHHmmss'); /*格式化时间*/
        var randNum = getRandomNum(0, 999999);
        var fileKey = formatDate + '_' + pad(randNum, 6);
        // console.log('[DEBUG]==fileKey: ' + fileKey);

        (function(req, res, fileKey){
            // 执行命令
            var cmd = './bin/gomod_build ' + filePath + ' ' + fileKey;
            // console.log('[DEBUG]==CMD: ' + cmd);
            exec(cmd, gomod_build_process(req, res, fileKey));
        })(req, res, fileKey);
    } else {
        res.send('文件上传失败');
    }
});

router.process_async = function(req, callback, callback_err) {
    var urllist = req.body.urllist;

    if (urllist && urllist.length > 0) {
        var filePath = createModFile(urllist);
        console.log('收到一个请求：' + urllist);
        if (filePath.length == 0) {
            res.send('文本格式不正确！');
        }

        var formatDate = moment().format('YYYYMMDDHHmmss'); /*格式化时间*/
        var randNum = getRandomNum(0, 999999);
        var fileKey = formatDate + '_' + pad(randNum, 6);
        // console.log('[DEBUG]==fileKey: ' + fileKey);

        var child = spawn('./bin/gomod_build', [
            filePath, fileKey
        ]);

        child.stdout.on('data', callback);
        child.stderr.on('data', callback_err);
    // } else {
    //     res.send('文件上传失败');
    }
};

module.exports = router;
